<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item> <i class="el-icon-lx-cascades"></i> 商品列表 </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-row :gutter="20">
                    <el-col :span="4">
                        <div class="grid-content bg-purple">
                            <el-input
                                v-model="query.name"
                                placeholder="商品名称"
                                class="handle-input mr10"
                                @keyup.enter.native="handleSearch"
                            ></el-input>
                        </div>
                    </el-col>

                    <el-col :span="4">
                        <div class="grid-content bg-purple">
                            <el-select v-model="query.categoryId" placeholder="--选择类别--" clearable filterable>
                                <el-option-group v-for="group in options" :key="group.label" :label="group.label">
                                    <el-option v-for="item in group.options" :key="item.value" :label="item.label" :value="item.value">
                                    </el-option>
                                </el-option-group>
                            </el-select>
                        </div>
                    </el-col>

                    <el-col :span="8">
                        <div class="grid-content bg-purple">
                            <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                            <el-button type="primary" icon="el-icon-plus" @click="$router.push({ path: '/goodsadd', query: { id: 0 } })"
                                >新增</el-button
                            >
                        </div>
                    </el-col>
                </el-row>
            </div>
            <el-table
                v-loading="loading"
                :data="tableData"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                row-key="id"
            >
                @selection-change="handleSelectionChange" >

                <el-table-column
                    width="300"
                    :show-overflow-tooltip="showtooltip"
                    class-name="user2"
                    prop="title"
                    label="商品名称"
                ></el-table-column>
                <el-table-column prop="image" label="图片" align="center">
                    <template slot-scope="scope">
                        <el-image prop="img" :src="scope.row.img" fit="contain" style="width: 40px">
                            <div slot="error" class="image-slot">
                                <i class="el-icon-picture-outline"></i>
                            </div>
                        </el-image>
                    </template>
                </el-table-column>
                <el-table-column prop="categoryId" :formatter="categoryFilter" label="所属类别" align="center"></el-table-column>
                <el-table-column prop="status.displayName" label="状态" align="center"></el-table-column>
                <el-table-column prop="onLinePrice" label="价格" :formatter="priceFilter" align="center"></el-table-column>
                <el-table-column prop="marketPrice" label="门市价" :formatter="priceFilter" align="center"></el-table-column>
                <el-table-column prop="sellCount" label="已售" align="center"></el-table-column>
     
                <!-- <el-table-column prop="sort" label="排序" align="center"></el-table-column> -->
                <el-table-column prop="distributionMoney" label="抽佣" align="center"></el-table-column>
                <el-table-column prop="creationTime" label="添加时间" align="center"></el-table-column>
                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                        <el-button type="text" icon="el-icon-edit" @click="$router.push({ path: '/goodsadd', query: { id: scope.row.id } })"
                            >编辑</el-button
                        >

                        <!-- <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">编辑</el-button> -->
                        <el-button type="text" icon="el-icon-delete" class="red" @click="handleDelete(scope.$index, scope.row)"
                            >删除</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    @size-change="handleSizeChange"
                    background
                    @current-change="handleCurrentChange"
                    :current-page="1"
                    :page-sizes="[10, 15, 20, 30]"
                    :page-size="10"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="pageTotal"
                >
                </el-pagination>
            </div>
        </div>
    </div>
</template>

<script>
import axios from 'axios';
export default {
    name: 'user_list',
    data() {
        return {
            options: [],
            value: '',
            query: {
                name: '',
                categoryId: '',
                pageIndex: 1,
                pageSize: 10
            },
            tableData: [],
            selectuser: [],
            multipleSelection: [],
            editVisible: false,
            pageTotal: 0,
            form: {},
            allRole: [],
            selectCategory: [],
            loading: false,
            showtooltip: true
        };
    },
    created() {
        this.loading = true;
        this.getCategorySelect();
        this.getData();
    },
    methods: {
        priceFilter(row, column, cellValue, index) {
            return '￥' + cellValue;
        },
        stateFilter(row, column) {
            var str = '';
            switch (row.status) {
                case 'On':
                    str = '上架';
                    break;
                case 'Of':
                    str = '已下架';
                    break;
                case 2:
                    str = '审核中';
                    break;
                case 3:
                    str = '售罄';
                    break;
                default:
                    str = row.state;
                    break;
            }
            return str;
        },
        categoryFilter(row, column) {
            var str = this.selectCategory.filter((c) => c.id == row.categoryId);
            if (str.length > 0) return str[0].title;
            else return '';
        },

        // 触发搜索按钮
        handleSearch() {
            this.query.pageIndex = 1;
            this.getData();
        },
        getData() {
            this.loading = true;
                       
            var parmas = {
                name: this.query.name,
                categoryId: this.query.categoryId || null,
                pageIndex: this.query.pageIndex,
                pageSize: this.query.pageSize
            };
            axios({
                url: config.gatewayUrl + '/api/product/paged',
                method: 'post',
                data: parmas
            }).then((res) => {
                // for (let i = 0; i < res.data.items.length; i++) {
                //     var image = String(res.data.items[i].image).split(',')[0];
                  
                //     if (image.indexOf('http') == -1) {
                //         res.data.list[i].img = config.fileUrl + image;
                        
                //     } else {
                //         res.data.list[i].img = image;
                //     }
                // }
                this.tableData = res.data.items;
                console.log( this.tableData);
                this.pageTotal = res.data.totalCount;
                this.loading = false;
            });
        },
        getCategorySelect() {
            var query = {
                title: '',
                parentId: null,
                pageIndex: 1,
                pageSize: 100
            };
            axios({
                url: config.gatewayUrl + '/api/product/cat/paged',
                method: 'post',
                data: query
            }).then((res) => {
                if (res.data && res.data.items.length > 0) {
                    this.selectCategory = res.data.items;


                    var firstCategory = res.data.items.filter(function (item) {
                        return item.parentId == 0;
                    });
                    var secondCategory = res.data.items.filter(function (item) {
                        return item.parentId > 0;
                    });

                    var st = [];

                    for (let i = 0; i < firstCategory.length; i++) {
                        var item = {
                            label: firstCategory[i].title,
                            options: []
                        };

                        var filterArray = secondCategory.filter(function (item) {
                            return item.parentId == firstCategory[i].id;
                        });
                        for (let k = 0; k < filterArray.length; k++) {
                            item.options.push({ value: filterArray[k].id, label: filterArray[k].title });
                        }

                        st.push(item);
                    }
                    this.options = st;
                }
            });
        },
        // 删除操作
        handleDelete(index, row) {
            // 二次确认删除
            var that = this;
            this.$confirm('确定要删除【' + row.name + '】吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    axios.get(config.gatewayUrl + '/set/user/delete/' + row.id).then((res) => {
                        that.getData();
                        that.tableData.splice(index, 1);
                        that.$message.success('删除成功');
                    });
                })
                .catch(() => {});
        },

        // 编辑操作
        handleEdit(index, row) {
            var length = this.allRole.length;

            var allRole = [];
            this.selectRole = [];
            if (length == 0) {
                axios
                    .post(config.gatewayUrl + '/set/role/getselectrole', {
                        tenantId: ''
                    })
                    .then((res) => {
                        console.log(res);
                        if (res.data) {
                            for (var i = 0; i < res.data.length; i++) {
                                allRole.push({
                                    key: res.data[i].id,
                                    label: res.data[i].roleName
                                });
                            }
                        }
                        this.allRole = allRole;
                    });
            }

            if (row) {
                this.idx = index;
                this.form = row;
                this.selectRole = row.roleId;
            }

            this.editVisible = true;

            // this.$refs.form.resetFields(); //移除表单校验并初始化表单，一般用于添加
            // this.$refs.form.clearValidate(); //移除表单校验，一般用于修改
        },
        // 保存编辑
        saveEdit(formName) {
            var that = this;
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    var dto = this.form;

                    axios
                        .post(config.gatewayUrl + '/set/user/post', dto)
                        .then((res) => {
                            if (res.data.result == false) {
                                that.$message.error(res.data.promptMsg);
                                console.log(res);
                            } else {
                                that.$refs.form.clearValidate();
                                //that.editVisible = false;
                                that.closeDialog();
                                that.$message.success(`保存成功!`);
                                that.getData();
                            }
                        })
                        .catch((error) => {
                            console.log(error); //  错误处理 相当于error
                        });
                    that.$refs.form.clearValidate();
                } else {
                    return false;
                }
            });
        },

        closeDialog() {
            this.selectRole = [];
            var that = this;
            //this.$refs.form.resetFields();
            this.form = {
                id: '',
                name: '',
                loginName: '',
                description: '',
                tenantId: ''
            };
            setTimeout(function () {
                that.$refs.form.clearValidate();
            }, 100);
            this.editVisible = false;
        },
        // 分页导航
        handlePageChange(val) {
            //跳转到
            this.$set(this.query, 'pageIndex', val);
            this.getData();
        },
        handleSizeChange(val) {
            //改变页码
            this.query.pageSize = val;
            this.getData();
        },
        handleCurrentChange(val) {
            //下一页console.log(`当前页: ${val}`);
            this.query.pageIndex = val;
            this.getData();
        }
    },
    watch: {}
};
</script>

<style scoped>
</style>
